<script>
export default {
	name: "AddTaskDialog"
}
</script>

<script setup>
import AddUserPopover from "@/components/addUserPopover/index.vue";
import moment from "moment";
import {nextTick, reactive, ref, watch} from "vue";
import api from "@/api";
import {ElMessage} from "element-plus";
import tool from "@/utils/tool";
import {useRoute} from "vue-router";


const props = defineProps({
	dialogAddForm: {
		type: Boolean,
		default: false
	},
	projectId: {
		type: String,
		default: ''
	},
	parentTaskId: {
		type: String,
		default: ''
	},
	taskResponsible: {
		type: String,
		default: ''
	},
	responsibleList: {
		type: Array,
		default() {
			return []
		}
	},
	empAddFlag: {
		type: Boolean,
		default: false
	},
})

var userInfo = tool.data.get("USER_INFO");
/*是否是员工*/
var isStaff = userInfo.role.includes('employee')
const route = useRoute()

/* 员工常规工作禁止删除负责人 */
const responsibleAvatarNone = ref(isStaff && route.name === 'regular' && !props.parentTaskId)

const dialogForm = ref(false)

const start1 = moment(new Date()).format("YYYY-MM-DD");
const form = ref({
	projectId: '',
	taskTitle: '',
	parentTaskId: '',
	taskType: '1',
	taskResponsible: '',//负责人id
	userList: [], //参与人列表
	partnerList: [], //合伙人列表
	responsibleList: [], //负责人列表
	startTime: start1,
	endTime: null,
	priority: '',
	label: '',
	taskDescription: '',
	status: '',
	priorityVe: false,
	feedtype: '0',
	feedcycle: '1',
	empAddFlag: false
})
const pickerOptions = ref({
	disabledDate(time) {
		// 获取当前年份
		const currentYear = new Date().getFullYear();
		// 创建当年的开始和结束时间
		const start = new Date(currentYear, 0, 1);
		const end = new Date(currentYear, 11, 31);
		// 返回是否禁用该日期
		return time.getTime() < start.getTime() || time.getTime() > end.getTime();
	}
})
watch(() => props.dialogAddForm, (props_dialogAddForm_n) => {
	dialogForm.value = props_dialogAddForm_n
	if (props_dialogAddForm_n) {
		nextTick(() => {
			addFormFef.value.resetFields()
			form.value.feedtype = '0'
			form.value.feedcycle = '1'
			const {projectId, parentTaskId, taskResponsible, responsibleList} = props.projectId
			form.value.projectId = props.projectId
			form.value.parentTaskId = props.parentTaskId
			form.value.taskResponsible = props.taskResponsible
			form.value.responsibleList = props.responsibleList
			form.value.empAddFlag = props.empAddFlag
		})
	}

}, {immediate: true})


const rules = reactive({
	taskTitle: [
		{required: true, trigger: 'blur'}
	],
	taskType: [
		{
			required: false,
			trigger: 'change'
		},
	],
	priority: [
		{
			required: true,
			trigger: 'change'
		},
	],
	label: [
		{
			required: false,
			trigger: 'change'
		},
	],
	responsibleList: [
		{
			required: true,
			trigger: 'change'
		}
	],
	taskDescription: [
		{
			required: false,
			trigger: 'change'
		},
	],
	status: [
		{
			required: false,
			trigger: 'change'
		},
	],
	priorityVe: [
		{
			required: false,
			trigger: 'change'
		},
	],
	endTime: [
		{
			type: 'date',
			required: true,
			trigger: 'change'
		},
	],
	feedcycle: [
		{
			required: true,
			trigger: 'change'
		},
	],
})

const shortcuts = [
	{
		text: '今天',
		value: new Date(),
	},
	{
		text: '明天',
		value: () => {
			const date = new Date()
			date.setTime(date.getTime() + 3600 * 1000 * 24)
			return date
		},
	},
	{
		text: '下周',
		value: () => {
			const date = new Date()
			date.setTime(date.getTime() + 3600 * 1000 * 24 * 7)
			return date
		},
	},{
		text: '长期',
		value: () => {
			const date = new Date()
			date.setTime(date.getTime() + 3600 * 1000 * 24 * 365 * 10)
			return date
		},
	}
]

const selectPriorityList = reactive([{
	value: '1',
	label: '一级'
}, {
	value: '2',
	label: '二级'
}, {
	value: '3',
	label: '三级'
}, {
	value: '4',
	label: '四级'
}])

const setSelectCycleList = () => {
	let data = [{
		value: '1',
		label: '每天'
	}, {
		value: '7',
		label: '每周'
	}, {
		value: '15',
		label: '每半月'
	}, {
		value: '30',
		label: '每月'
	}, {
		value: '90',
		label: '每季度'
	}, {
		value: '180',
		label: '每半年'
	}, {
		value: '365',
		label: '每年'
	}]
	if (form.value.feedtype === '1') {
		return data.slice(0, -2);
	}
	return data
}

/**
 * 删除已选用户
 * @param user
 */
const delSelectUser = (user, formName) => {
	let index = form.value[formName].indexOf(user)
	form.value[formName].splice(index, 1)
}


/**
 * 已选择负责人集合
 * @param userList
 * @return data
 */
const getSelectResponsible = (userList) => {
	form.value.taskResponsible = userList[0].id
	form.value.responsibleList = userList
}

/**
 * 已选择参与人集合
 * @param userList
 * @return data
 */
const getSelectUsers = (userList) => {
	form.value.taskResponsible = userList[0].id
	form.value.partnerList = userList
}

const pickerOptions0 = (time) => {
	// console.log(time.getFullYear())
	// 不能选择之前的时间 || 不可跨年
	if (time.getTime() < Date.now() - 8.64e7) {
		return true;
	} else {
		return false;
	}
}

watch(()=>form.value.endTime,(endTime_n)=>{
	// 监听 如果时间比当前日期早，则强制重置为当前日期
	if (new Date(endTime_n).getTime() < Date.now() - 8.64e7 ) {
		form.value.endTime = moment().format('YYYY-MM-DD');
	}
})


/* 要求反馈周期切换类型 */
const feedtypeChange = () => {
	if (form.value.feedtype === '1') {
		if (form.value.feedcycle === '30' || !form.value.feedcycle) {
			form.value.feedcycle = '1'
		}
		form.value.feedback = '1'
	} else {
		form.value.feedback = ''
	}
}

const feedcycleChange = () => {
	form.value.feedback = '1'
}

const selectFrequencyList = () => {
	// if (form.value.feedback !== '30') {
	return 360
	// }
}

const setFrequencyLabel = (option) => {
	const data = {
		'1': '天',
		'7': '周',
		'15': '半月',
		'30': '月',
		'90': '季度',
		'180': '半年',
		'365': '年',
		/*'360': '长期'*/
	}
	return option + data[form.value.feedcycle]
}

const weekOptions = [{
	value: '1',
	label: '星期一'
}, {
	value: '2',
	label: '星期二'
}, {
	value: '3',
	label: '星期三'
}, {
	value: '4',
	label: '星期四'
}, {
	value: '5',
	label: '星期五'
}, {
	value: '6',
	label: '星期六'
}, {
	value: '7',
	label: '星期日'
}]
const twoweekOptions = [{
	value: '1',
	label: '第一天'
}, {
	value: '2',
	label: '第二天'
}, {
	value: '3',
	label: '第三天'
}, {
	value: '4',
	label: '第四天'
}, {
	value: '5',
	label: '第五天'
}, {
	value: '6',
	label: '第六天'
}, {
	value: '7',
	label: '第七天'
}, {
	value: '8',
	label: '第八天'
}, {
	value: '9',
	label: '第九天'
}, {
	value: '10',
	label: '第十天'
}, {
	value: '11',
	label: '第十一天'
}, {
	value: '12',
	label: '第十二天'
}, {
	value: '13',
	label: '第十三天'
}, {
	value: '14',
	label: '第十四天'
}, {
	value: '15',
	label: '第十五天'
}]
const mouthOptions = [{
	value: '1',
	label: '1号'
}, {
	value: '2',
	label: '5号'
}, {
	value: '3',
	label: '10号'
}, {
	value: '4',
	label: '15号'
}, {
	value: '5',
	label: '20号'
}, {
	value: '6',
	label: '25号'
}, {
	value: '7',
	label: '30号'
}]
const seasonOptions = [{
	value: '1',
	label: '季度第一天'
}, {
	value: '2',
	label: '季度第十天'
}, {
	value: '3',
	label: '季度第三十天'
}, {
	value: '4',
	label: '季度第四十五天'
}, {
	value: '5',
	label: '季度第六十天'
}, {
	value: '6',
	label: '季度最后十天'
}, {
	value: '7',
	label: '季度最后五天'
}, {
	value: '8',
	label: '季度最后一天'
}
]
const longOptions = [{
	value: '1',
	label: '每周'
}, {
	value: '2',
	label: '每半月'
}, {
	value: '3',
	label: '每月'
}, {
	value: '4',
	label: '每季度'
}, {
	value: '5',
	label: '每半年'
}, {
	value: '6',
	label: '每年'
}
]

const addFormFef = ref(null)
/**
 * 新增提交
 */
const addSubmit = async () => {
	await addFormFef.value.validate(vaild => {
		// if (form.value.responsibleList.length === 0) {
		// 	ElNotification({
		// 		title: '警告',
		// 		message: '请选择负责人',
		// 		type: 'warning',
		// 	})
		// }
		if (vaild) {
			// 任务类型
			if (props.empAddFlag) {
				form.value.taskType = '2'
			}
			form.value.projectId = props.projectId
			api.task.add.post(form.value).then(ref => {
				dialogForm.value = false
				ElMessage.success('新增成功！')
			})
		}
	})
}

const emit = defineEmits(['close'])

/* 关闭 */
const dialogClose = () => {
	emit('close')
}

const ruleFeedcycle = (key, prop)=>{
	console.log(11222)
	if(responsibleAvatarNone.value){
		if (form.value[key]) {
			rules[prop][0].required = true
			return prop
		}
	}
	return ''
}

</script>

<template>
	<el-dialog
		v-model="dialogForm"
		:close-on-click-modal="false"
		class="task-details-dialog"
		@close="dialogClose"
		title="新建任务"
	>
		<el-form
			ref="addFormFef"
			:model="form"
			:rules="rules"
			:show-message="false"
			label-position="top"
			label-suffix="："
		>
			<el-form-item label="任务描述" prop="taskTitle">
				<el-input
					v-model="form.taskTitle"
					autocomplete="off"
					placeholder="请输入描述"
					type="textarea"
					:rows="5"
					show-word-limit
					:maxlength="500"
					autofocus
				/>
			</el-form-item>
			<el-row>
				<!--					<el-col :span="12">-->
				<!--						<el-form-item label="类型" prop="taskType">-->
				<!--							<el-select v-model="form.taskType">-->
				<!--								<el-option label="任务" value="0"/>-->
				<!--								<el-option label="事务" value="1"/>-->
				<!--							</el-select>-->
				<!--						</el-form-item>-->
				<!--					</el-col>-->
				<!--			截至时间		-->
				<!--					<el-col :span="12">-->
				<!--						<el-form-item label="接收时间" prop="endTime">-->
				<!--							<el-date-picker-->
				<!--								readonly-->
				<!--								v-model="form.startTime"-->
				<!--								placeholder="请选择日期"-->
				<!--								type="date"-->
				<!--								value-format="YYYY-MM-DD"-->
				<!--							/>-->
				<!--						</el-form-item>-->
				<!--					</el-col>-->

				<el-col :span="12" v-if="form.taskType !== '0'">
					<el-form-item label="优先级" prop="priority">
						<el-select v-model="form.priority" placeholder="请选择优先级">
							<el-option
								v-for="option in selectPriorityList"
								:key="option.label"
								:label="option.label"
								:value="option.value">
								{{ option.label }}
							</el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="负责人" prop="responsibleList">
						<div class="select-user">
							<div class="select-user-list">
								<div v-for="user in form.responsibleList"
									 :key="user.id"
									 class="user-avatar select-user-avatar"
								>
									<el-tooltip :content="user.orgName+' '+user.cn" effect="light" placement="top">
										<div>
											<el-avatar :size="28">{{
													user.cn.substring(user.cn.length - 2)
												}}
											</el-avatar>
											<el-avatar
												v-if="!responsibleAvatarNone"
												:size="28"
												class="del-user"
												@click="delSelectUser(user,'responsibleList')">
												<el-icon color="red">
													<Delete/>
												</el-icon>
											</el-avatar>
										</div>
									</el-tooltip>
								</div>
							</div>
							<AddUserPopover
								v-if="form.responsibleList.length < 1"
								:select="form.responsibleList"
								:size="0"
								:empAddFlag="form.empAddFlag"
								@submit="getSelectResponsible"
							/>
						</div>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="要求完成时间" prop="endTime">
						<el-date-picker
							v-model="form.endTime"
							:shortcuts="shortcuts"
							placeholder="请选择日期"
							type="date"
							:disabled-date="pickerOptions0"
							value-format="YYYY-MM-DD"
						/>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="要求反馈周期" prop="feedcycle">
						<template #label>
							要求反馈周期：
							<el-radio-group
								v-model="form.feedtype"
								size="small"
								class="form-label-radio"
								@change="feedtypeChange"
							>
								<el-radio-button label="0">默认</el-radio-button>
								<el-radio-button label="1">自定义</el-radio-button>
							</el-radio-group>
						</template>
						<el-select
							v-model="form.feedcycle"
							placeholder="请选择"
							:style="form.feedtype === '1'?'width:100px;':''"
							@change="feedcycleChange"
						>
							<el-option
								v-for="option in setSelectCycleList()"
								:key="option.label"
								:label="option.label"
								:value="option.value">
								{{ option.label }}
							</el-option>
						</el-select>
						<div v-if="form.feedtype === '1' " class="feedType1-main">
							<el-select
								v-if="form.feedcycle === '1' "
								v-model="form.feedback"
								placeholder="请选择自定义时段（天）"
							>
								<el-option
									v-for="option in selectFrequencyList()"
									:key="option + '' "
									:label="setFrequencyLabel(option)"
									:value="option  + '' ">
								</el-option>
							</el-select>
							<el-select
								v-if="form.feedcycle === '7' "
								v-model="form.feedback"
								placeholder="请选择自定义时段（星期）"
								class="feedType1-select"
							>
								<el-option
									v-for="option in weekOptions"
									:key="option.value"
									:label="option.label"
									:value="option.value">
								</el-option>
							</el-select>
							<el-select
								v-if="form.feedcycle === '15' "
								v-model="form.feedback"
								placeholder="请选择自定义时段（半月）"
								class="feedType1-select"
							>
								<el-option
									v-for="option in twoweekOptions"
									:key="option.value"
									:label="option.label"
									:value="option.value">
								</el-option>
							</el-select>
							<el-select
								v-if="form.feedcycle === '30' "
								v-model="form.feedback"
								placeholder="请选择自定义时段（月）"
								class="feedType1-select"
							>
								<el-option
									v-for="option in mouthOptions"
									:key="option.value"
									:label="option.label"
									:value="option.value">
								</el-option>
							</el-select>
							<el-select
								v-if="form.feedcycle === '90' "
								v-model="form.feedback"
								placeholder="请选择自定义时段（季度）"
								class="feedType1-select"
							>
								<el-option
									v-for="option in seasonOptions"
									:key="option.value"
									:label="option.label"
									:value="option.value">
								</el-option>
							</el-select>
<!--							<el-select
								v-if="form.feedcycle === '180' "
								v-model="form.feedback"
								placeholder="请选择自定义时段（半年）"
								class="feedType1-select"
							>
								<el-option
									v-for="option in harfyearOptions"
									:key="option.value"
									:label="option.label"
									:value="option.value">
								</el-option>
							</el-select>
							<el-select
								v-if="form.feedcycle === '360' "
								v-model="form.feedback"
								placeholder="请选择自定义时段（年）"
								class="feedType1-select"
							>
								<el-option
									v-for="option in yearOptions"
									:key="option.value"
									:label="option.label"
									:value="option.value">
								</el-option>
							</el-select>-->
						</div>
					</el-form-item>
				</el-col>
				<!--					<el-col :span="12">-->
				<!--						<el-form-item label="要求反馈周期" prop="feedback">-->
				<!--							<template #label>-->
				<!--								要求反馈周期1-->
				<!--							</template>-->
				<!--							<el-select v-model="form.feedback" placeholder="请选择反馈周期">-->
				<!--								<el-option-->
				<!--									v-for="option in selectCycleList"-->
				<!--									:key="option.label"-->
				<!--									:label="option.label"-->
				<!--									:value="option.value">-->
				<!--									{{ option.label }}-->
				<!--								</el-option>-->
				<!--							</el-select>-->
				<!--						</el-form-item>-->
				<!--					</el-col>-->

			</el-row>
		</el-form>
		<template #footer>
			  <span class="dialog-footer">
				<el-button text @click="dialogForm = false">取消</el-button>
				<el-button type="primary" @click="addSubmit">
				  确定
				</el-button>
			  </span>
		</template>
	</el-dialog>

</template>

<style scoped>
.select-user {
	display: flex;

	.select-user-list {
		display: flex;

		> div {
			margin-right: 10px;
		}

		.user-avatar {
			> div {
				position: relative;

				&:hover {

					.del-user {
						display: unset ;
						position: absolute;
						right: 0px;
						bottom: 0px;
						background: rgba(16, 16, 16, 0.39);
						top: 0px;
					}
				}

				.del-user {
					display: none;
				}
			}
		}
	}
}

.feedType1-main {
	display: inline-block;
	width: calc(100% - 150px);
	margin-left: 10px;
}
</style>
